package handler

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/yourusername/rss-reader-ai/internal/service"
)

// =====================================================
// ArticleHandler 文章处理器
// =====================================================

// ArticleHandler 文章HTTP处理器
type ArticleHandler struct {
	articleService service.ArticleService
}

// NewArticleHandler 创建文章处理器
func NewArticleHandler(articleService service.ArticleService) *ArticleHandler {
	return &ArticleHandler{
		articleService: articleService,
	}
}

// RegisterRoutes 注册路由
func (h *ArticleHandler) RegisterRoutes(router *gin.RouterGroup) {
	articles := router.Group("/articles")
	{
		articles.GET("", h.ListArticles)                // 获取文章列表
		articles.GET("/:id", h.GetArticle)              // 获取文章详情
		articles.POST("/:id/read", h.MarkAsRead)        // 标记已读
		articles.POST("/:id/unread", h.MarkAsUnread)    // 标记未读
		articles.POST("/batch/read", h.BatchMarkAsRead) // 批量标记已读
		articles.POST("/:id/favorite", h.ToggleFavorite) // 切换收藏
		articles.PUT("/:id/note", h.UpdateNote)         // 更新笔记
		articles.DELETE("/:id", h.DeleteArticle)        // 删除文章
		articles.POST("/batch/delete", h.BatchDelete)   // 批量删除
		articles.GET("/search", h.SearchArticles)       // 搜索文章
		articles.GET("/stats", h.GetStats)              // 统计信息
		articles.POST("/export", h.ExportMarkdown)      // 导出Markdown
	}
}

// =====================================================
// API 请求/响应结构
// =====================================================

// UpdateNoteRequest 更新笔记请求
type UpdateNoteRequest struct {
	Note string `json:"note"`
}

// BatchMarkAsReadRequest 批量标记已读请求
type BatchMarkAsReadRequest struct {
	IDs []int64 `json:"ids" binding:"required"`
}

// BatchDeleteRequest 批量删除请求
type BatchDeleteRequest struct {
	IDs []int64 `json:"ids" binding:"required"`
}

// ExportMarkdownRequest 导出Markdown请求
type ExportMarkdownRequest struct {
	IDs []int64 `json:"ids" binding:"required"`
}

// StatsResponse 统计响应
type StatsResponse struct {
	UnreadCount   int64 `json:"unread_count"`
	FavoriteCount int64 `json:"favorite_count"`
}

// =====================================================
// API 处理器
// =====================================================

// ListArticles 获取文章列表
// @Summary 获取文章列表
// @Tags Article
// @Produce json
// @Param feed_id query int false "订阅源ID"
// @Param is_read query bool false "是否已读"
// @Param is_favorite query bool false "是否收藏"
// @Param start_date query string false "开始日期 (2006-01-02)"
// @Param end_date query string false "结束日期 (2006-01-02)"
// @Param page query int false "页码" default(1)
// @Param size query int false "每页数量" default(20)
// @Success 200 {object} PageResponse{data=[]model.Article}
// @Router /api/articles [get]
func (h *ArticleHandler) ListArticles(c *gin.Context) {
	// 1. 解析查询参数
	filter := &service.ArticleFilter{}

	// FeedID
	if feedIDStr := c.Query("feed_id"); feedIDStr != "" {
		feedID, err := strconv.ParseInt(feedIDStr, 10, 64)
		if err == nil {
			filter.FeedID = &feedID
		}
	}

	// IsRead
	filter.IsRead = GetBoolQuery(c, "is_read")

	// IsFavorite
	filter.IsFavorite = GetBoolQuery(c, "is_favorite")

	// StartDate
	if startDateStr := c.Query("start_date"); startDateStr != "" {
		startDate, err := time.Parse("2006-01-02", startDateStr)
		if err == nil {
			filter.StartDate = &startDate
		}
	}

	// EndDate
	if endDateStr := c.Query("end_date"); endDateStr != "" {
		endDate, err := time.Parse("2006-01-02", endDateStr)
		if err == nil {
			filter.EndDate = &endDate
		}
	}

	// 分页参数
	page := GetIntQuery(c, "page", 1)
	size := GetIntQuery(c, "size", 20)

	// 2. 调用 Service
	articles, total, err := h.articleService.ListArticles(filter, page, size)
	if err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	// 3. 返回分页响应
	PageSuccessResponse(c, articles, total, page, size)
}

// GetArticle 获取文章详情
// @Summary 获取文章详情
// @Tags Article
// @Produce json
// @Param id path int true "文章ID"
// @Success 200 {object} Response{data=model.Article}
// @Router /api/articles/{id} [get]
func (h *ArticleHandler) GetArticle(c *gin.Context) {
	// 解析路径参数
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		ErrorResponse(c, http.StatusBadRequest, "无效的ID")
		return
	}

	// 调用 Service
	article, err := h.articleService.GetArticle(id)
	if err != nil {
		ErrorResponse(c, http.StatusNotFound, err.Error())
		return
	}

	// 返回响应
	SuccessResponse(c, article)
}

// MarkAsRead 标记文章为已读
// @Summary 标记文章为已读
// @Tags Article
// @Produce json
// @Param id path int true "文章ID"
// @Success 200 {object} Response
// @Router /api/articles/{id}/read [post]
func (h *ArticleHandler) MarkAsRead(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		ErrorResponse(c, http.StatusBadRequest, "无效的ID")
		return
	}

	if err := h.articleService.MarkAsRead(id); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// MarkAsUnread 标记文章为未读
// @Summary 标记文章为未读
// @Tags Article
// @Produce json
// @Param id path int true "文章ID"
// @Success 200 {object} Response
// @Router /api/articles/{id}/unread [post]
func (h *ArticleHandler) MarkAsUnread(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		ErrorResponse(c, http.StatusBadRequest, "无效的ID")
		return
	}

	if err := h.articleService.MarkAsUnread(id); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// BatchMarkAsRead 批量标记已读
// @Summary 批量标记已读
// @Tags Article
// @Accept json
// @Produce json
// @Param request body BatchMarkAsReadRequest true "文章ID列表"
// @Success 200 {object} Response
// @Router /api/articles/batch/read [post]
func (h *ArticleHandler) BatchMarkAsRead(c *gin.Context) {
	var req BatchMarkAsReadRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		ErrorResponse(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	if err := h.articleService.BatchMarkAsRead(req.IDs); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// ToggleFavorite 切换收藏状态
// @Summary 切换收藏状态
// @Tags Article
// @Produce json
// @Param id path int true "文章ID"
// @Success 200 {object} Response
// @Router /api/articles/{id}/favorite [post]
func (h *ArticleHandler) ToggleFavorite(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		ErrorResponse(c, http.StatusBadRequest, "无效的ID")
		return
	}

	if err := h.articleService.ToggleFavorite(id); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// UpdateNote 更新文章笔记
// @Summary 更新文章笔记
// @Tags Article
// @Accept json
// @Produce json
// @Param id path int true "文章ID"
// @Param note body UpdateNoteRequest true "笔记内容"
// @Success 200 {object} Response
// @Router /api/articles/{id}/note [put]
func (h *ArticleHandler) UpdateNote(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		ErrorResponse(c, http.StatusBadRequest, "无效的ID")
		return
	}

	var req UpdateNoteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		ErrorResponse(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	if err := h.articleService.UpdateNote(id, req.Note); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// DeleteArticle 删除文章
// @Summary 删除文章
// @Tags Article
// @Produce json
// @Param id path int true "文章ID"
// @Success 200 {object} Response
// @Router /api/articles/{id} [delete]
func (h *ArticleHandler) DeleteArticle(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		ErrorResponse(c, http.StatusBadRequest, "无效的ID")
		return
	}

	if err := h.articleService.DeleteArticle(id); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// BatchDelete 批量删除文章
// @Summary 批量删除文章
// @Tags Article
// @Accept json
// @Produce json
// @Param request body BatchDeleteRequest true "文章ID列表"
// @Success 200 {object} Response
// @Router /api/articles/batch/delete [post]
func (h *ArticleHandler) BatchDelete(c *gin.Context) {
	var req BatchDeleteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		ErrorResponse(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	if err := h.articleService.BatchDeleteArticles(req.IDs); err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	SuccessResponse(c, nil)
}

// SearchArticles 搜索文章
// @Summary 搜索文章
// @Tags Article
// @Produce json
// @Param q query string true "搜索关键词"
// @Param page query int false "页码" default(1)
// @Param size query int false "每页数量" default(20)
// @Success 200 {object} PageResponse{data=[]model.Article}
// @Router /api/articles/search [get]
func (h *ArticleHandler) SearchArticles(c *gin.Context) {
	// 解析参数
	keyword := c.Query("q")
	if keyword == "" {
		ErrorResponse(c, http.StatusBadRequest, "搜索关键词不能为空")
		return
	}

	page := GetIntQuery(c, "page", 1)
	size := GetIntQuery(c, "size", 20)

	// 调用 Service
	articles, total, err := h.articleService.SearchArticles(keyword, page, size)
	if err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	// 返回响应
	PageSuccessResponse(c, articles, total, page, size)
}

// GetStats 获取统计信息
// @Summary 获取统计信息
// @Tags Article
// @Produce json
// @Success 200 {object} Response{data=StatsResponse}
// @Router /api/articles/stats [get]
func (h *ArticleHandler) GetStats(c *gin.Context) {
	// 获取未读数
	unreadCount, err := h.articleService.GetUnreadCount()
	if err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	// 获取收藏数
	favoriteCount, err := h.articleService.GetFavoriteCount()
	if err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	// 返回响应
	SuccessResponse(c, StatsResponse{
		UnreadCount:   unreadCount,
		FavoriteCount: favoriteCount,
	})
}

// ExportMarkdown 导出文章为Markdown
// @Summary 导出文章为Markdown
// @Tags Article
// @Accept json
// @Produce text/plain
// @Param request body ExportMarkdownRequest true "文章ID列表"
// @Success 200 {string} string "Markdown内容"
// @Router /api/articles/export [post]
func (h *ArticleHandler) ExportMarkdown(c *gin.Context) {
	var req ExportMarkdownRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		ErrorResponse(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	// 调用 Service
	markdown, err := h.articleService.ExportToMarkdown(req.IDs)
	if err != nil {
		ErrorResponse(c, http.StatusInternalServerError, err.Error())
		return
	}

	// 返回Markdown文本
	c.Header("Content-Type", "text/markdown; charset=utf-8")
	c.Header("Content-Disposition", "attachment; filename=articles.md")
	c.String(http.StatusOK, markdown)
}
